#!/usr/bin/bash

# Convert all jpg files in folder Upload/Images/ and file size greater than 80KB to webp format
# before converting, backup images to folder Upload/Images-Original/


# Define source and backup directories
SOURCE_DIR="Upload/Images"
BACKUP_DIR="Upload/Images-Original"

# Create the backup directory if it doesn't exist
mkdir -p "$BACKUP_DIR"

# Find all jpg files larger than 80KB in the source directory
find "$SOURCE_DIR" -type f -iname "*.jpg" -size +80k | while read -r file; do
    # Check if the file already exists in the backup directory
    backup_file="$BACKUP_DIR/$(basename "$file")"
    if [ ! -f "$backup_file" ]; then
        # Backup the file to the backup directory
        cp "$file" "$BACKUP_DIR"
        # Convert the file to webp format
        cwebp "$backup_file" -q 80 -o "$file" >/dev/null 2>&1
        echo Convert success $file
    else
        # Skip conversion if the backup already exists
        echo "Skipping conversion for $file as it already has a backup."
    fi
done